﻿namespace VisualSVN.Core.Licensing
{
    using System;

    public class Base32Decoder
    {
        private static byte CharToVal(char c)
        {
            c = char.ToLower(c);
            if (('0' <= c) && (c <= '9'))
            {
                return (byte) TrimNegative((byte) (c - '0'));
            }
            return (byte) TrimNegative((byte) ((c - 'a') + 10));
        }

        private static byte[] ConvertFromKey(string key, byte base2)
        {
            if (IsEmpty(key))
            {
                return null;
            }
            uint num = (uint) Math.Floor((double) ((((double) base2) / 8.0) * key.Length));
            byte[] buffer = new byte[num];
            if (IsEmpty(buffer))
            {
                return null;
            }
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = 0;
            }
            int num3 = 0;
            int num4 = key.Length - 1;
            byte num5 = 0;
            while ((num4 >= 0) && (num3 < (num * 8)))
            {
                byte num6 = CharToVal(key[num4--]);
                int num7 = (buffer[num3 / 8] + (num6 << (num3 % 8))) + num5;
                num5 = (byte) (num7 / 0x100);
                buffer[num3 / 8] = (byte) (num7 % 0x100);
                num3 += base2;
            }
            return buffer;
        }

        public static byte[] Decode(string str)
        {
            return ConvertFromKey(str, 5);
        }

        private static bool IsEmpty(Array value)
        {
            if (value != null)
            {
                return (value.Length == 0);
            }
            return true;
        }

        private static bool IsEmpty(string value)
        {
            if (value != null)
            {
                return (value.Length == 0);
            }
            return true;
        }

        private static int TrimNegative(int x)
        {
            if (x < 0)
            {
                return 0;
            }
            return x;
        }
    }
}

